package com.wocai.jrt.admin.user.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.admin.common.bean.Node;
import com.wocai.jrt.admin.user.model.Authorities;
import com.wocai.jrt.admin.user.model.AuthoritiesBean;
import com.wocai.jrt.admin.user.model.AuthoritiesBean.Criteria;
import com.wocai.jrt.admin.user.model.ModuleMenu;
import com.wocai.jrt.admin.user.model.Roles;
import com.wocai.jrt.admin.user.service.spi.AuthoritiesService;
import com.wocai.jrt.admin.user.service.spi.ModuleMenuService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 权限表控制器
 * @author yinlei
 * @date 2015-7-6 11:40:41
 */
@Controller
@RequestMapping("/authorities")
public class AuthoritiesAction extends GenericAction<Authorities> {
	private static final Logger LOGGER = LoggerFactory.getLogger(AuthoritiesAction.class);
	
	@Inject
	private AuthoritiesService authoritiesServiceImpl;
	
	@Inject
	private ModuleMenuService moduleMenuServiceImpl;
	
	/**
     * 获得权限表List，初始化列表页。
     * @param model 参数
     * @return 权限表List
     */
    @RequestMapping("/list")
    public String list(Authorities model, Map<String, Object> maps) {
    	try {
            List<ModuleMenu> menuList = moduleMenuServiceImpl.loadModuleList();
            maps.put("menuList", menuList);
		} catch (Exception e) {
			LOGGER.error("init authorites list error, msg=[{}].", e.getMessage());
		}
        return "authorities/list";
    }
	
    /**
     * 查询权限，以及初始化列表页面
     * @param auth 参数
     * @return 查询结果
     */
    @ResponseBody
    @RequestMapping("/query")
    public Map<String, Object> query(@RequestBody Authorities auth) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		AuthoritiesBean params = buildQuery(auth);
    		List<Authorities> list = authoritiesServiceImpl.queryForList(params);
    		
    		// 统计的时候，不需要分页
    		params.setStart(null);
    		int totalRecord = authoritiesServiceImpl.count(params);
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("authorities query success.");
    		}
    		
    		//？在服务端判断，还是客户端好呢？还是在上面的查询中关联呢
    		// 先这样，做个匹配也是很快的
    		List<ModuleMenu> menuList = moduleMenuServiceImpl.loadModuleList();
    		for (Authorities bean : list) {
    			for (ModuleMenu menu : menuList) {
    				if (bean.getModuleId().equals(menu.getModuleId())) {
    					bean.setModuleId(menu.getModuleName());
    					break; // 找到了，中断内层循环
    				}
    			}
    		}
    		
    		// jQuery datatable 就是这样的参数，阿西吧
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("authorities query error, msg=[{}]", e.getMessage());
		}
        return result;
    }
    
    private AuthoritiesBean buildQuery(Authorities auth) {
    	AuthoritiesBean params = new AuthoritiesBean();
    	params.setDistinct(auth.isDistinct());
    	params.setPageSize(auth.getPageSize());
    	params.setStart(auth.getStart());
    	
    	Criteria criteria = params.createCriteria();
    	
    	String authName = auth.getAuthName();
    	if (StringUtils.isNotBlank(authName)) {
    		criteria.andAuthNameLike(authName);
    	}
    	
    	String moduleId = auth.getModuleId();
    	if (StringUtils.isNotBlank(moduleId)) {
    		criteria.andModuleIdEqualTo(moduleId);
    	}
    	
    	Integer enabled = auth.getEnabled();
    	if (enabled != null) {
    		criteria.andEnabledEqualTo(enabled);
    	}
    	
    	Boolean showMenu = auth.getShowMenu();
    	if (showMenu != null) {
    		criteria.andShowMenuEqualTo(showMenu);
    	}
    	
    	criteria.andOrgIdEqualTo(UserUtils.getOrgId());
    	
    	return params;
    }
    
	/**
	 * 获得权限表List Tree，Json格式。
	 * @param model 参数
	 * @return 权限表List Tree
	 */
	@ResponseBody
	@RequestMapping("/tree")
	public Node tree(Roles model) {
		Node root = new Node();
		try {
			root = authoritiesServiceImpl.getAuthTree(model);
		} catch (Exception e) {
			LOGGER.error("build authorities tree error, msg=[{}].", e.getMessage());
		}
		return root;
	}
	
	/**
     * 跳转到新增页面
     * @return 新增页面逻辑视图
     */
    @RequestMapping("/add")
    public String add(Map<String, Object> maps) {
    	try {
    		List<ModuleMenu> menuList = moduleMenuServiceImpl.loadModuleList();
            maps.put("menuList", menuList);
		} catch (Exception e) {
			LOGGER.error("query module menu error, msg=[{}].", e.getMessage());
			return "common/error";
		}
        return "authorities/add";
    }
    
    /**
     * 执行实际的新增操作
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     */
    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonBean doAdd(@RequestBody Authorities model) {
    	JsonBean bean = new JsonBean();
    	try {
    		model.setOrgId(UserUtils.getOrgId());
    		
    		int result = authoritiesServiceImpl.saveAuthorities(model);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
            } else {
                bean.setMessage(ERROR);
            }
		} catch (Exception e) {
			bean.setMessage(ERROR);
			LOGGER.error(e.getMessage());
		}
        return bean;
    }
    
    /**
     * 跳转到编辑信息页面
     * @param model 查询参数，携带ID
     * @return 编辑页面
     */
    @ResponseBody
    @RequestMapping("/edit")
    public Authorities edit(Authorities model) {
    	try {
    		model = authoritiesServiceImpl.get(model.getAuthId());
    		
    		List<ModuleMenu> list = moduleMenuServiceImpl.loadModuleList();
    		model.setMenuList(list);
		} catch (Exception e) {
			LOGGER.error("edit, query authorities error, msg=[{}], id=[{}].", e.getMessage(), model.getAuthId());
		}
        return model;
    }
    
    /**
     * 更新权限表信息
     * @param model 要更新的权限表信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody Authorities model) {
    	JsonBean bean = new JsonBean();
    	if (StringUtils.isBlank(model.getAuthId())) {
    		bean.setMessage("params's authId cannot be null.");
    		return bean;
    	}
    	try {
    		int result = authoritiesServiceImpl.updateAuthorities(model);
            if (result == 1) {
            	LOGGER.info("update authorities success, authId=[{}].", model.getAuthId());
                bean.setMessage(SUCCESS);
                bean.setCode(1);
            } else {
                bean.setMessage(ERROR);
            }
		} catch (Exception e) {
			LOGGER.error("update record error, msg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 删除权限表信息
     * @param id 要删除的权限表ID
     */
    @ResponseBody
    @RequestMapping("/delete")
    public JsonBean delete(String id) {
    	JsonBean bean = new JsonBean();
    	if (StringUtils.isBlank(id)) {
    		bean.setMessage("params cannot be null.");
    		return bean;
    	}
    	try {
    		int result = authoritiesServiceImpl.deleteAuthorities(id);
            if (result == 1) {
            	LOGGER.info("delete authorities success, authId=[{}].", id);
                bean.setMessage(SUCCESS);
                bean.setCode(1);
            } else {
                bean.setMessage(ERROR);
            }
		} catch (Exception e) {
			LOGGER.error("delete record error, msg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
}
